import 'package:flutter/rendering.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class ColorPreview extends StatefulWidget{

  final Color previewColor;
  final double width;
  final double height;

  const ColorPreview({
    @required this.previewColor,
    this.width = 50,//提供默认值，如果使用过程中，不附带该参数，则默认值为50
    this.height = 50//提供默认值,如果使用过程中，不附带该参数，则默认值为50
  }) : super();


  @override
  State<StatefulWidget> createState() => new ColorPreviewState();

}

class ColorPreviewState extends State<ColorPreview>{

  @override
  void initState() {
    super.initState();

  }

  @override
  Widget build(BuildContext context) {

    return new GestureDetector(

      onTapDown: (details){

          print("按下自定义的颜色预览组件,该组件的长度为:${context.size.width},高度为:${context.size.height}");
      },

      child: new CustomPaint(
        painter: new ColorPainter(bgColor: widget.previewColor),
        size: Size(widget.width, widget.height),
      ),

    );

  }

}


class ColorPainter extends CustomPainter{

  final Color bgColor;

  const ColorPainter({
    this.bgColor,
  }) : super();


//  ColorPainter({@required this.bgColor}) : super(); //  double _width;

  @override
  void paint(Canvas canvas, Size size) {

    if (bgColor != null ){

      canvas.drawRect(Rect.fromPoints(Offset(0, 0), Offset(size.width, size.height)),
          Paint()..color = bgColor..style = PaintingStyle.fill);

    }

  }

  @override
  bool shouldRepaint(ColorPainter oldDelegate) {

    return bgColor!=oldDelegate.bgColor;
  }

}